﻿using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.UI;

namespace Runner {
    public class Runner {
        private static readonly BinaryFormatter bf = new BinaryFormatter();
        private static readonly LosFormatter lf = new LosFormatter();

        [Serializable]
        public class Result {
            public object Value { get; set; }
        }

        public static int Main(string[] args) {
            var pipename = args[2];
            using (var pipe = new NamedPipeClientStream(".", pipename, PipeDirection.Out)) {
                pipe.Connect();
                try {
                    var type = Type.GetType(args[0]);
                    var method = type.GetMethod(args[1]);
                    var instance = Activator.CreateInstance(type);
                    var parameters = args.Skip(3).Select(p => lf.Deserialize(p)).ToArray();
                    var returnValue = method.Invoke(instance, parameters);
                    bf.Serialize(pipe, new Result { Value = returnValue });
                    return 0;
                } catch (Exception e) {
                    bf.Serialize(pipe, new Result { Value = e });
                    return 1;
                }
            }
        }
    }
}